<?php
/**
 * 应用公共函数库文件
 */
use think\facade\Request;
use think\facade\Cache;
use app\common\model\Setting;
use hema\wechat\Driver as Wechat;
use app\common\model\Order as OrderModel;
use app\common\model\User as UserModel;
use app\common\model\ShopClerk as ShopClerkModel;

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

/**
 * POST请求
 * @param  [type] $url     [description]
 * @param  array  $data    [description]
 * @param  array  $headers [description]
 * @return [type]          [description]
 */
function http_post($url,$data = array(),$headers=array())
{
    $curl = curl_init();
    if( count($headers) >= 1 ){
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    if (count($data) >= 1 AND !isset($data['media'])){
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
    }elseif(count($data) == 0){
        $data = '{}';
    }
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    return $output;
}

/**
 * 发送订阅消息 - 点餐
 * @param  string $mode     receive=商家接单通知 horseman=骑手取货通知 delivery=订单配送通知 take=取餐提醒 finish=订单完成通知 refund=退款状态通知
 * @param  [type] $order 订单
 */
function food_post_tpl(string $mode = '',$order_id)
{
    //获取订阅消息配置
    $order = OrderModel::detail($order_id);
    //获取订阅消息配置
    $values = Setting::getItem('wxapptpl');
    $data = [];
    $template_id = '';
    //商家接单通知
    if($mode=='receive' AND !empty($values['receive'])){
        $template_id = trim($values['receive']);
        $data = [
            'thing2' => [
                'value' => $order['shop']['shop_name']//商家名称{{thing2.DATA}}
            ],
            'character_string6' => [
                'value' => $order['order_no']//订单编号{{character_string6.DATA}}
            ],
            'phrase7' => [
                'value' => '已接单' //订单状态{{phrase7.DATA}}
            ],
            'phone_number10' => [
                'value' => date('Y-m-s h:i',time())//接单时间{{phone_number10.DATA}}
            ],
            'thing5' => [
                'value' => '商家备餐中，点击查看详情>>' //温馨提示{{thing5.DATA}}
            ]
        ];
    }
    //骑手取货通知
    if($mode=='horseman' AND !empty($values['horseman'])){
        $template_id = trim($values['horseman']);
        $data = [
            'thing1' => [
                'value' => $order['shop']['shop_name']//商家{{thing1.DATA}}
            ],
            'phrase2' => [
                'value' => '骑手已接单' //状态{{phrase2.DATA}}
            ],
            'thing4' => [
                'value' => '待骑手配送，点击查看详情>>' //备注{{thing4.DATA}}
            ]
        ];
    }
    //取餐提醒
    if($mode=='take' AND !empty($values['take'])){
        $template_id = trim($values['take']);
        if($order['order_mode']['value']==30){
            $status = '到店自取';
        }else{
            $status = '堂食排号';
        }
        $data = [
            'thing23' => [
                'value' => $order['shop']['shop_name']//门店名称{{thing23.DATA}}
            ],
            'character_string12' => [
                'value' => $order['row_no']//取餐编号{{character_string12.DATA}}
            ],
            'phrase30' => [
                'value' => $status //订单类型{{phrase30.DATA}}
            ],
            'phrase16' => [
                'value' => '待领取' //订单状态{{phrase16.DATA}}
            ],
            'thing7' => [
                'value' => '请前往领餐处，点击查看详情>>' //温馨提醒{{thing7.DATA}}
            ]
        ];
    }
    //订单配送通知
    if($mode=='delivery' AND !empty($values['delivery'])){
        $template_id = trim($values['delivery']);
        $data = [
            'thing1' => [
                'value' => $order['shop']['shop_name']//出餐门店{{thing1.DATA}}
            ],
            'character_string2' => [
                'value' => $order['order_no']//订单号{{character_string2.DATA}}
            ],
            'phrase15' => [
                'value' => '配送中' //订单状态{{phrase15.DATA}}
            ],
            'time4' => [
                'value' => date('Y-m-s h:i',time())//送出时间{{time4.DATA}}
            ],
            'thing5' => [
                'value' => '30分钟内送达，点击查看详情>>' //备注{{thing5.DATA}}
            ]
        ];
    }
    //订单完成通知
    if($mode=='finish' AND !empty($values['finish'])){
        $template_id = trim($values['finish']);
        if($order['order_mode']['value']==30){
            $status = '到店自取';
        }else{
            if($order['row_no'] == ''){
                $status = '堂食扫码';
            }else{
                $status = '堂食排号';
            }
        }
        $data = [
            'thing13' => [
                'value' => $order['shop']['shop_name']//门店名称{{thing13.DATA}}
            ],
            'phrase11' => [
                'value' => '已完成'//订单状态{{phrase11.DATA}}
            ],
            'thing14' => [
                'value' => $status //订单类型{{thing14.DATA}}
            ],
            'time12' => [
                'value' => date('Y-m-s h:i',time())//完成时间{{time12.DATA}}
            ],
            'thing5' => [
                'value' => '订单餐食已送完，点击查看详情>>' //备注{{thing5.DATA}}
            ]
        ];
    }
    //退款状态通知
    if($mode=='refund' AND !empty($values['refund'])){
        $template_id = trim($values['refund']);
        if($order['refund_status']['value']==20){
            $status = '退款成功';
            $msg = '退款已原路返回，点击查看详情>>';
        }else{
            $status = '退款失败';
            $msg = '不符合退款要求，点击查看详情>>';
        }
        $data = [
            'phrase1' => [
                'value' => $status//退款状态 {{phrase1.DATA}}
            ],
            'amount2' => [
                'value' => '￥'.$order['refund_price'].'元'//退款金额 {{amount2.DATA}}
            ],
            'time4' => [
                'value' => date('Y-m-s h:i',time()) //处理时间 {{time4.DATA}}
            ],
            'thing5' => [
                'value' => $msg //温馨提示 {{thing5.DATA}}
            ]
        ];
    }
    //发送订阅消息
    if(sizeof($data) > 0 AND $template_id != ''){
        $wx = new Wechat;
        $queryarr = [
            'touser' => $order['user']['open_id'],
            'template_id' => $template_id,
            'page' => 'pages/order/detail?order_id='.$order_id,
            'data' => $data
        ];
        $wx->sedSubscribeMsg($order['applet_id'],$queryarr);
    }
    return true;
}

/**
* 验证手机号是否正确
*/
function is_phone($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,3,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
}

/**
 * 生成订单号
 */
function order_no()
{
    return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

/**
 * 将xml转为array
*/
function _xml_to_arr($xml) {
    $res = @simplexml_load_string ( $xml,NULL, LIBXML_NOCDATA );
    $res = json_decode ( json_encode ( $res), true );
    return $res;
}

/**
 * 获取规格信息
 */
function get_many_spec_data($spec_rel, $skuData)
{
    // spec_attr
    $specAttrData = [];
    foreach ($spec_rel as $item) {
        if (!isset($specAttrData[$item['spec_id']])) {
            $specAttrData[$item['spec_id']] = [
                'group_id' => $item['spec']['spec_id'],
                'group_name' => $item['spec']['spec_name'],
                'spec_items' => [],
            ];
        }
        $specAttrData[$item['spec_id']]['spec_items'][] = [
            'item_id' => $item['spec_value_id'],
            'spec_value' => $item['spec_value'],
        ];
    }

    // spec_list
    $specListData = [];
    foreach ($skuData as $item) {
        $image = (isset($item['image']) && !empty($item['image'])) ? $item['image'] : ['file_id' => 0, 'url' => ''];
        $specListData[] = [
            'goods_spec_id' => $item['goods_spec_id'],
            'spec_sku_id' => $item['spec_sku_id'],
            'rows' => [],
            'form' => [
                'image_id' => $image['file_id'],
                'image_url' => $image['url'],
                'goods_no' => $item['goods_no'],
                'goods_price' => $item['goods_price'],
                'line_price' => $item['line_price'],
                'stock_num' => $item['stock_num'],
                'goods_weight' => $item['goods_weight']
            ],
        ];
    }
    return ['spec_attr' => array_values($specAttrData), 'spec_list' => $specListData];
}

/**
 * 多维数组按照指定字段升/降序排列
 */
function arr_sort(array $data, string $field, string $order = 'desc')
{
    foreach($data as $val){
        $key_arrays[]=$val[$field];
    }
    if($order == 'desc'){
        array_multisort($key_arrays,SORT_DESC,SORT_NUMERIC,$data);
    }else{
        array_multisort($key_arrays,SORT_ASC,SORT_NUMERIC,$data);
    }
    return $data;
}

















    
    /**
     * 商户管理员 - 账户资金变动提醒 - 公众号
     */
    function sand_account_change_msg($title,$pay,$surplus,$user_id,$applet_id = 0)
    { 
        $webtplmsg = Setting::getItem('webtplmsg',$applet_id);    //获取模板消息编号
        if(empty($webtplmsg['balance'])){
            return true;
        }
        $foodhelp = Setting::getItem('foodhelp',0);  //获取商家助手小程序
        $msg = [
            'touser' => '',
            'template_id' => trim($webtplmsg['balance']),
            'miniprogram' => [
                'appid' => $foodhelp['app_id'],
                'pagepath' => 'pages/index/index'
            ],
            'data' => [
                'first' => [
                    'value' => '请您核实下列项目',
                    'color' => '#173177'
                ],
                'keyword1' => [
                    'value' => $title,//交易类型
                    'color' => '#173177'
                ],
                'keyword2' => [
                    'value' => '￥'.$pay.'元',//交易金额
                    'color' => '#173177'
                ],
                'keyword3' => [
                    'value' => date('Y/m/d H:i:s',time()),//交易时间
                    'color' => '#173177'
                ],
                'keyword4' => [
                    'value' => '￥'.$surplus.'元',//账户余额
                    'color' => '#173177'
                ],
                'remark' => [
                    'value' => '如有疑问请及时联系我们!',
                    'color' => '#173177'
                ]
            ]
        ];
        return send_wechat_msg($msg,$user_id);
    }
    
    /**
     * 商户管理员 - 申请受理通知 - 公众号
     */
    function sand_apply_msg($name,$title,$user_id,$applet_id = 0)
    {
        $webtplmsg = Setting::getItem('webtplmsg',$applet_id);    //获取模板消息编号
        if(empty($webtplmsg['apply'])){
            return true;
        }
        $foodhelp = Setting::getItem('foodhelp',0);  //获取商家助手小程序
        $msg = [
            'touser' => '',
            'template_id' => trim($webtplmsg['apply']),
            'miniprogram' => [
                'appid' => $foodhelp['app_id'],
                'pagepath' => 'pages/index/index'
            ],
            'data' => [
                'first' => [
                    'value' => '您的导购申请已受理',
                    'color' => '#173177'
                ],
                'keyword1' => [
                    'value' => $name,//申请人
                    'color' => '#173177'
                ],
                'keyword2' => [
                    'value' => $title,//类型
                    'color' => '#173177'
                ],
                'keyword3' => [
                    'value' => date('Y/m/d H:i:s',time()),//时间
                    'color' => '#173177'
                ],
                'remark' => [
                    'value' => '感谢您的支持！',
                    'color' => '#173177'
                ]
            ]
        ];
        return send_wechat_msg($msg,$user_id);
    }
    
    /**
     * 商户管理员 - 申请状态更新通知 - 公众号
     */
    function sand_examine_msg($id,$title,$status,$user_id,$applet_id = 0)
    {
        $webtplmsg = Setting::getItem('webtplmsg',$applet_id);    //获取模板消息编号
        if(empty($webtplmsg['examine'])){
            return true;
        }
        $foodhelp = Setting::getItem('foodhelp',0);  //获取商家助手小程序
        $msg = [
            'touser' => '',
            'template_id' => trim($webtplmsg['examine']),
            'miniprogram' => [
                'appid' => $foodhelp['app_id'],
                'pagepath' => 'pages/index/index'
            ],
            'data' => [
                'first' => [
                    'value' => '最新申请状态',
                    'color' => '#173177'
                ],
                'keyword1' => [
                    'value' => $title,//申请类型
                    'color' => '#173177'
                ],
                'keyword2' => [
                    'value' => $id,//申请编号
                    'color' => '#173177'
                ],
                'keyword3' => [
                    'value' => date('Y/m/d H:i:s',time()),//申请时间
                    'color' => '#173177'
                ],
                'keyword4' => [
                    'value' => $status,//当前状态
                    'color' => '#173177'
                ],
                'remark' => [
                    'value' => '请及时关注新的动态提醒。',
                    'color' => '#173177'
                ]
            ]
        ];
        return send_wechat_msg($msg,$user_id);
    }

    /**
     * 商户管理员 - 试用申请成功通知 - 公众号
     */
    function sand_testing_msg($title,$time,$user_id,$applet_id = 0)
    {
        $webtplmsg = Setting::getItem('webtplmsg',$applet_id);    //获取模板消息编号
        if(empty($webtplmsg['testing'])){
            return true;
        }
        $foodhelp = Setting::getItem('foodhelp',0);  //获取商家助手小程序
        $msg = [
            'touser' => '',
            'template_id' => trim($webtplmsg['testing']),
            'miniprogram' => [
                'appid' => $foodhelp['app_id'],
                'pagepath' => 'pages/index/index'
            ],
            'data' => [
                'first' => [
                    'value' => '恭喜您获得试用特权',
                    'color' => '#173177'
                ],
                'keyword1' => [
                    'value' => $title,//申请项目
                    'color' => '#173177'
                ],
                'keyword2' => [
                    'value' => date('Y/m/d H:i:s',$time),//有效期至
                    'color' => '#173177'
                ],
                'remark' => [
                    'value' => '感谢您的使用。',
                    'color' => '#173177'
                ]
            ]
        ];
        return send_wechat_msg($msg,$user_id);
    }

    /**
     * 商户骑手 - 抢单提醒 - 公众号
     */
    function sand_grab_msg($order,$applet_id = 0)
    {
        $webtplmsg = Setting::getItem('webtplmsg',$applet_id);    //获取模板消息编号
        if(empty($webtplmsg['grab'])){
            return true;
        }
        $foodhelp = Setting::getItem('foodhelp',0);  //获取商家助手小程序
        $msg = [
            'touser' => '',
            'template_id' => trim($webtplmsg['grab']),
            'miniprogram' => [
                'appid' => $foodhelp['app_id'],
                'pagepath' => 'pages/order/index'
            ],
            'data' => [
                'first' => [
                    'value' => '您有新订单可抢单',
                    'color' => '#173177'
                ],
                'keyword1' => [
                    'value' => $order['shop']['shop_name'],//商家名称
                    'color' => '#173177'
                ],
                'keyword2' => [
                    'value' => $order['shop']['address'],//配送起点
                    'color' => '#173177'
                ],
                'keyword3' => [
                    'value' => $order['address']['detail'],//配送终点
                    'color' => '#173177'
                ],
                'keyword4' => [
                    'value' => $order['shop']['phone'],//商家电话
                    'color' => '#173177'
                ],
                'remark' => [
                    'value' => '有疑问请联系商家，点击查看详情>>',
                    'color' => '#173177'
                ]
            ]
        ];
        $model = new ShopClerkModel;
        $clerk = $model->getAll($order['shop_id'],30); 
        for($n=0;$n<sizeof($clerk);$n++){
            if($clerk[$n]['user_id'] > 0){
                send_wechat_msg($msg,$clerk[$n]['user_id']);
            }
        }
    }

    /**
     * 商户店长 - 退款申请通知 - 公众号
     */
    function sand_refund_msg($order,$applet_id = 0)
    {
        $webtplmsg = Setting::getItem('webtplmsg',$applet_id);    //获取模板消息编号
        if(empty($webtplmsg['refund'])){
            return true;
        }
        $foodhelp = Setting::getItem('foodhelp',0);  //获取商家助手小程序
        $msg = [
            'touser' => '',
            'template_id' => trim($webtplmsg['refund']),
            'miniprogram' => [
                'appid' => $foodhelp['app_id'],
                'pagepath' => 'pages/order/index'
            ],
            'data' => [
                'first' => [
                    'value' => '收到一条新退款, 请尽快受理',
                    'color' => '#173177'
                ],
                'keyword1' => [
                    'value' => $order['shop']['shop_name'],//门店
                    'color' => '#173177'
                ],
                'keyword2' => [
                    'value' => $order['order_no'],//订单编号
                    'color' => '#173177'
                ],
                'keyword3' => [
                    'value' => '￥'.$order['refund_price'].'元',//退款金额
                    'color' => '#173177'
                ],
                'keyword4' => [
                    'value' => date('Y/m/d H:i:s',time()),//退款时间
                    'color' => '#173177'
                ],
                'remark' => [
                    'value' => $order['refund_desc'],
                    'color' => '#173177'
                ]
            ]
        ];
        $model = new ShopClerkModel;
        $clerk = $model->getAll($order['shop_id'],20); 
        for($n=0;$n<sizeof($clerk);$n++){
            if($clerk[$n]['user_id'] > 0){
                send_wechat_msg($msg,$clerk[$n]['user_id']);
            }
        }
    }

    /**
     * 商户店长 新订单提醒模板消息 - 公众号
     */
    function sand_new_order_msg($order,$applet_id = 0)
    {
        $webtplmsg = Setting::getItem('webtplmsg',$applet_id);    //获取模板消息编号
        if(empty($webtplmsg['new_order'])){
            return true;
        }
        $foodhelp = Setting::getItem('foodhelp',0);  //获取商家助手小程序
        if($order['order_mode']['value']==30){
            $title = '自取';
        }elseif($order['order_mode']['value']==20){
            $title = '外卖';
        }else{
            $title = '堂食';
        }
        $msg = [
            'touser' => '',
            'template_id' => trim($webtplmsg['new_order']),
            'miniprogram' => [
                'appid' => $foodhelp['app_id'],
                'pagepath' => 'pages/order/index'
            ],
            'data' => [
                'first' => [
                    'value' => '收到一个新的'.$title.'订单',
                    'color' => '#173177'
                ],
                'keyword1' => [
                    'value' => $order['order_no'],
                    'color' => '#173177'
                ],
                'keyword2' => [
                    'value' => '￥'.$order['pay_price'].'元',
                    'color' => '#173177'
                ],
                'keyword3' => [
                    'value' => $order['create_time'],
                    'color' => '#173177'
                ],
                'remark' => [
                    'value' => '请及时处理您的订单。',
                    'color' => '#173177'
                ]
            ]
        ];
        $model = new ShopClerkModel;
        $clerk = $model->getAll($order['shop_id'],20); 
        for($n=0;$n<sizeof($clerk);$n++){
            if($clerk[$n]['user_id'] > 0){
                send_wechat_msg($msg,$clerk[$n]['user_id']);
            }
        }
    }

    /**
     * 发布模板消息 - 公众号
     */
    function send_wechat_msg(array $msg, $user_id, $applet_id = 0)
    {
        $user = UserModel::getUser(['user_id' => $user_id]);
        $msg['touser'] = $user['open_id'];
        $wx = new Wechat;
        $wx->sendWechatMsg($applet_id,$msg);
        return true;
    }
    
/**
 * 生成门店订单排号(取餐码)
 */
function row_no($applet_id,$shop_id)
{
    if($row_no = Cache::get('order_row_no_'.$applet_id.'_'.$shop_id)){
        $row_no = (int)$row_no;
        $row_no++;  
    }else{
        $row_no = 1;
    }
    //有效期时间,截至到当天23:59:59
    $time = strtotime(date('Y-m-d').'23:59:59')-time();
    Cache::set('order_row_no_'.$applet_id.'_'.$shop_id, $row_no,$time);
    $str_row_no = (string)$row_no;
    $lan = strlen($str_row_no);
    for($n=$lan;$n<4;$n++){
        $str_row_no = '0'.$str_row_no;
    }
    return $str_row_no;
}


/**
 * 生成密码hash值
 */
function hema_hash($password)
{
    return md5(md5($password) . 'hema_salt_SmTRx');
}

/**
 * 写入日志
 */
function write_log($values, $dir)
{
    if (is_array($values))
        $values = print_r($values, true);
    // 日志内容
    $content = '[' . date('Y-m-d H:i:s') . ']' . PHP_EOL . $values . PHP_EOL . PHP_EOL;
    try {
        // 文件路径
        $filePath = $dir . '/logs/';
        // 路径不存在则创建
        !is_dir($filePath) && mkdir($filePath, 0755, true);
        // 写入文件
        return file_put_contents($filePath . date('Ymd') . '.log', $content, FILE_APPEND);
    } catch (\Exception $e) {
        return false;
    }
}


if (!function_exists('array_column')) {
    /**
     * array_column 兼容低版本php
     * (PHP < 5.5.0)
     * @param $array
     * @param $columnKey
     * @param null $indexKey
     * @return array
     */
    function array_column($array, $columnKey, $indexKey = null)
    {
        $result = array();
        foreach ($array as $subArray) {
            if (is_null($indexKey) && array_key_exists($columnKey, $subArray)) {
                $result[] = is_object($subArray) ? $subArray->$columnKey : $subArray[$columnKey];
            } elseif (array_key_exists($indexKey, $subArray)) {
                if (is_null($columnKey)) {
                    $index = is_object($subArray) ? $subArray->$indexKey : $subArray[$indexKey];
                    $result[$index] = $subArray;
                } elseif (array_key_exists($columnKey, $subArray)) {
                    $index = is_object($subArray) ? $subArray->$indexKey : $subArray[$indexKey];
                    $result[$index] = is_object($subArray) ? $subArray->$columnKey : $subArray[$columnKey];
                }
            }
        }
        return $result;
    }
}

/**
 * 多维数组合并
 */
function array_merge_multiple($array1, $array2)
{
    $merge = $array1 + $array2;
    $data = [];
    foreach ($merge as $key => $val) {
        if (
            isset($array1[$key])
            && is_array($array1[$key])
            && isset($array2[$key])
            && is_array($array2[$key])
        ) {
            $data[$key] = array_merge_multiple($array1[$key], $array2[$key]);
        } else {
            $data[$key] = isset($array2[$key]) ? $array2[$key] : $array1[$key];
        }
    }
    return $data;
}

/**
 * 获取全局唯一标识符
 */
function get_guid_v4($trim = true)
{
    // Windows
    if (function_exists('com_create_guid') === true) {
        $charid = com_create_guid();
        return $trim == true ? trim($charid, '{}') : $charid;
    }
    // OSX/Linux
    if (function_exists('openssl_random_pseudo_bytes') === true) {
        $data = openssl_random_pseudo_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);    // set version to 0100
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);    // set bits 6-7 to 10
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }
    // Fallback (PHP 4.2+)
    mt_srand((double)microtime() * 10000);
    $charid = strtolower(md5(uniqid(rand(), true)));
    $hyphen = chr(45);                  // "-"
    $lbrace = $trim ? "" : chr(123);    // "{"
    $rbrace = $trim ? "" : chr(125);    // "}"
    $guidv4 = $lbrace .
        substr($charid, 0, 8) . $hyphen .
        substr($charid, 8, 4) . $hyphen .
        substr($charid, 12, 4) . $hyphen .
        substr($charid, 16, 4) . $hyphen .
        substr($charid, 20, 12) .
        $rbrace;
    return $guidv4;
}

/**
 * 获取当前系统版本号
 */
function get_version()
{
    return json_decode(file_get_contents('./version.json'), true);
}

/**
 * 清空缓存目录
 */
function deldir($path){
    //如果是目录则继续
    if(is_dir($path)){
        //扫描一个文件夹内的所有文件夹和文件并返回数组
        $p = scandir($path);
        foreach($p as $val){
            //排除目录中的.和..
            if($val !="." && $val !=".."){
                //如果是目录则递归子目录，继续操作
                if(is_dir($path.$val)){
                    //子目录中操作删除文件夹和文件
                    deldir($path.$val.'/');
                    //目录清空后删除空文件夹
                    @rmdir($path.$val.'/');
                }else{
                    //如果是文件直接删除
                    unlink($path.$val);
                }
            }
        }
    }
}

/**
 * 下划线转驼峰
 */
function camelize($uncamelized_words, $separator = '_')
{
    $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
    return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
}

/**
 * 驼峰转下划线
 */
function uncamelize($camelCaps, $separator = '_')
{
    return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
}

/**
 * 获取当前域名及根路径
 */
function base_url()
{
    static $baseUrl = '';
    if (empty($baseUrl)) {
        $request = Request::instance();
        // url协议
        $scheme = $request->scheme();
        // url子目录
        $rootUrl = root_url();
        // 拼接完整url
        $baseUrl = "{$scheme}://" . $request->host() . $rootUrl;
    }
    return $baseUrl;
}

/**
 * 获取当前uploads目录访问地址
 */
function uploads_url()
{
    return base_url() . 'uploads';
}

/**
 * 获取当前url的子目录路径
 */
function root_url()
{
    static $rootUrl = '';
    if (empty($rootUrl)) {
        $request = Request::instance();
        $subUrl = str_replace('\\', '/', dirname($request->baseFile()));
        $rootUrl = $subUrl . ($subUrl === '/' ? '' : '/');
    }
    return $rootUrl;
}

/**
 * 获取当前的应用名称
 */
function app_name()
{
    return app('http')->getName();
}

/**
 * 获取web根目录
 */
function web_path()
{
    static $webPath = '';
    if (empty($webPath)) {
        $request = Request::instance();
        $webPath = dirname($request->server('SCRIPT_FILENAME')) . DIRECTORY_SEPARATOR;
    }
    return $webPath;
}


/**
 * 判断是否为自定义索引数组
 */
function is_assoc(array $array)
{
    if (empty($array)) return false;
    return array_keys($array) !== range(0, count($array) - 1);
}

//去除二维数组重复值,默认重复保留前面的值
/*
  *array 二维数组
  *keyid 需要判断是否重复的项目
*/
function array_repeat($array,$keyid)
{
    $array =array_values($array);     
    //提取需要判断的项目变成一维数组
    $a = array_tq($array,$keyid);
     
    //去除一维数组重复值
    $a =array_unique($a);
    //提取二维数组项目值
    foreach($array[0] AS$key=>$value)
    {
        $akey[] =$key;
    }
    //重新拼接二维数组
    foreach($akey AS$key=>$value)
    {
        $b = array_tq($array,$value);
        foreach($a AS$key2=>$value2)
        {
            $c[$key2][$value] =$b[$key2];
        }
    }
    return $c;
}

//提取二维数组项目
function array_tq($array, $aval="")
{
    foreach($array AS $key => $value)
    {
        $result[] = $value[$aval];
    }
    return $result;
}

/**
 * 二维数组排序
 */
function array_sort($arr, $keys, $desc = false)
{
    $key_value = $new_array = array();
    foreach ($arr as $k => $v) {
        $key_value[$k] = $v[$keys];
    }
    if ($desc) {
        arsort($key_value);
    } else {
        asort($key_value);
    }
    reset($key_value);
    foreach ($key_value as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}

/**
 * 隐藏敏感字符
 */
function substr_cut($value)
{
    $strlen = mb_strlen($value, 'utf-8');
    if ($strlen <= 1) return $value;
    $firstStr = mb_substr($value, 0, 1, 'utf-8');
    $lastStr = mb_substr($value, -1, 1, 'utf-8');
    return $strlen == 2 ? $firstStr . str_repeat('*', $strlen - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
}



/**
 * 时间戳转换日期
 */
function format_time($timeStamp)
{
    return date('Y-m-d H:i:s', $timeStamp);
}

/**
 * 左侧填充0
 * @param $value
 * @param $padLength
 * @return string
 */
function pad_left($value, $padLength = 2)
{
    return \str_pad($value, $padLength, "0", STR_PAD_LEFT);
}

/**
 * 重写trim方法 (解决int类型过滤后后变为string类型)
 * @param $str
 * @return string
 */
function my_trim($str)
{
    return is_string($str) ? trim($str) : $str;
}

/**
 * 重写htmlspecialchars方法 (解决int类型过滤后后变为string类型)
 * @param $string
 * @return string
 */
function my_htmlspecialchars($string)
{
    return is_string($string) ? htmlspecialchars($string) : $string;
}

/**
 * 根据指定长度截取字符串
 */
function str_substr($str, $length = 30)
{
    if (strlen($str) > $length) {
        $str = mb_substr($str, 0, $length);
    }
    return $str;
}

/**
 * 文本左斜杠转换为右斜杠
 */
function convert_left_slash(string $string)
{
    return str_replace('\\', '/', $string);
}

/**
 * 隐藏手机号中间四位 13012345678 -> 130****5678
 */
function hide_mobile(string $mobile)
{
    return substr_replace($mobile, '****', 3, 4);
}
